package imageCompress

import (
	"fmt"
	"github.com/nfnt/resize"
	"image"
	"image/jpeg"
	"image/png"
	"io"
	"log"
	"os"
	"strings"
)

type InputArgs struct {
	OutputPath string //** 输出目录
	LocalPath  string //** 输入的目录或文件路径
	Quality    int    //** 质量
	Width      int    //** 宽度尺寸，像素单位
	Format     string //** 格式
}

//图片压缩
func ImageCompress(temp ,temp1 interface{},to string, quality int,format string) error {
	/** 读取文件 */
	var origin image.Image
	var config image.Config
	var temp2 io.Reader

	var err error
	var typeImage int64

	fileOrigin:=temp.(io.Reader)
	temp2 =temp1.(io.Reader)

	format = strings.ToLower(format)
	/** jpg 格式 */
	if format == "jpg" || format == "jpeg" {
		typeImage = 1
		origin, err = jpeg.Decode(fileOrigin)
		if err != nil {
			fmt.Println("jpeg.Decode(fileOrigin)",err)
			return err
		}
		config, err = jpeg.DecodeConfig(temp2)
		if err != nil {
			fmt.Println("jpeg.DecodeConfig(temp)",err)
			return err
		}
	} else if format == "png" {
		typeImage = 0
		origin, err = png.Decode(fileOrigin)
		if err != nil {
			fmt.Println("png.Decode(fileOrigin)",err)
			return err
		}
		config, err = png.DecodeConfig(temp2)
		if err != nil {
			fmt.Println("png.DecodeConfig(temp)",err)
			return err
		}
	}

	//fmt.Println("高度",config.Height)
	//fmt.Println("宽度",config.Width)

	/**** 做等比缩放 ****/
	//width := uint(base) /** 基准 */
	//height := uint(base * config.Height / config.Width)

	width :=uint(config.Width)
	height :=uint(config.Height)
	canvas := resize.Thumbnail(width, height, origin, resize.Lanczos3)

	file_out, err := os.Create(to)

	if err != nil {
		fmt.Println("图片保存失败")
		log.Fatal(err)
		return err
	}

	defer file_out.Close()

	if typeImage == 0 {
		err = png.Encode(file_out, canvas)
		if err != nil {
			fmt.Println("压缩图片失败")
			return err
		}
	} else {
		err = jpeg.Encode(file_out, canvas, &jpeg.Options{quality})
		if err != nil {
			fmt.Println("压缩图片失败")
			return err
		}
	}
	return nil
}
